local skynet = require "skynet"
local PlayerProto = require "modules.player.PlayerProto"
local PlayerService = require "modules.player.PlayerService"
local PlayerConst = require "modules.player.PlayerConst"
local Platform = require "global.Platform"
local Services = require "global.Services"
---@type PlayerMgr
local PlayerMgr = Services.PLAYER_MGR

local handler = {}
function handler.CS_HEART_BEAT(player)
    return PlayerProto.HEART_BEAT
end

function handler.CS_LOGOUT(player)
    -- 记录日志等
    PlayerMgr:logout(player.id)
end

function handler.CS_LOGIN(connection, data)
    local resultCode = PlayerConst.LOGIN_CODE
    local code, authData = Platform.auth(data)
    if code ~= 1 then
        -- 授权失败
        GWARNF("auth failed, code: %s, msg: %s", code, authData)
        return {
            code = resultCode.AUTH_FAILED,
            msg = string.format("授权失败, 错误码: %s", code)
        }
    end

    local playerId = authData.id
    -- TODO:是否被禁用(ip, 账号)
    local player = PlayerService:login(playerId)
    if not PlayerMgr:login(playerId, connection.fd, connection.gate) then
        return {
            code = 3,
            msg = "玩家已经登录"
        }
    end

    connection.id = playerId
    -- 登录成功
    return {
        code = 1,
        player = player
    }
end

return handler
